package com.xingfei.blog.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

public class Utils {
	public static final String PATTERN_FULL_NUMBER = "^\\d+$";
	
	
	private static String propFilePath=null;
	private static Properties properties = new Properties();
	private static Map<String, ArrayList<String>> localDefineMap = new HashMap<String, ArrayList<String>>(); 
	public static final String DEFAULT_PROPERTY_FILE = "config.properties";
	
	
	//********************************************************************************************************************
    //																				Ⅰ通用工具				
    //********************************************************************************************************************
	
	/**
	 * object转换为字符串
	 * @param obj
	 * @return String
	 */
	public static String getStrValue(Object obj){
		if(obj==null){
			return null;
		}
		return obj.toString();
	}
	
	/**
	 * object转换为Integer
	 * @param obj
	 * @return
	 */
	public static int getIntegerValue(Object obj){
		if(obj==null){
			return 0;
		}
		try{
		return Integer.parseInt(obj.toString());
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}
	
	/**
	 * 获取类在service中注册的名称。类的首字母缩写
	 * @param clazz
	 * @return
	 */
	public static String gainClassServiceName(Class clazz){
		String name=clazz.getSimpleName();
		char first=Character.toLowerCase(name.charAt(0));
		name=first+name.substring(1);
		return name;
	}
	
	/**
	 * 判断字符串是否为空
	 * @param str
	 * @return boolean
	 */
	public static boolean isEmpty(String str){
		return str == null || str.trim().length() <= 0;
	}
	
	/**
	 * 将String类型转换成int型
	 * @param String sourceString
	 * @return int 转换后的int型
	 */
	public static int toNumber(String sourceString) {
		return toNumber(sourceString, 0);
	}

	/**
	 * @reload
	 * 将String类型转换成int型数字
	 * @param String sourceString
	 * @param int defaultValue
	 * @return int 转换后的int型
	 */
	public static int toNumber(String sourceString, int defaultValue) {
		return isDigitalNumber(sourceString)&& Long.parseLong(sourceString) <= Integer.MAX_VALUE ? Integer.parseInt(sourceString) : defaultValue;
	}

	/**
	 * 将String类型转换成long型
	 * @param String sourceString
	 * @return long 转换后的long型

	 */
	public static long toLongNumber(String sourceString) {
		return toLongNumber(sourceString, 0);
	}

	/**
	 * @reload
	 * 将String类型转换成long型数字
	 * @param String sourceString
	 * @param long defaultValue
	 * @return long 转换后的long型
	 */
	public static long toLongNumber(String sourceString, long defaultValue) {
		return isDigitalNumber(sourceString) ? Long.parseLong(sourceString) : defaultValue;
	}
	
	/**
	 * 判断是否为数字
	 * @param String sourceString
	 * @return boolean
	 */
	public static boolean isDigitalNumber(String sourceString) {
		return sourceString != null
				&& sourceString.matches(PATTERN_FULL_NUMBER);
	}
	
	/**
	 * 判断是否为
	 * @param url
	 * @return boolean
	 */
	public static boolean isURL(String url) {
		return url.startsWith("http") && !url.startsWith("http://127.0.0.1") && !url.startsWith("http://localhost");
	}
	
	/**
	 * Double格式化
	 * @param d
	 * @param pattern
	 * @return double
	 */
	public static double formatDouble(double d,String pattern){
		  DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();
		  // format.applyPattern("0.00");
		   format.applyPattern(pattern);
		   String s = format.format(d);
		   d = Double.parseDouble(s);
		   return d;
	}
	
	/**
	 * **********
	 * @param is
	 * @return 
	 */
	public static boolean loadProperties(InputStream is){
        try {
            properties.load(is);
        } catch (IOException e) {
            return false;
        } finally {
        	try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return true;
    }
	
	/**
	 * **********
	 * @param fileName
	 * @return boolean
	 */
	public static boolean loadProperties(String fileName){
          try {
        	  propFilePath=fileName;
			InputStream inputStream=new FileInputStream(fileName);
			return loadProperties(inputStream);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
    }
	
	/**
	 * **********
	 * @param key
	 * @return
	 */
	public static String getProperty(String key){
        return properties.getProperty(key);
    }

	/**
	 * **********
	 * @param key
	 * @param defaultValue
	 * @return string
	 */
	public static String getProperty(String key, String defaultValue){
        return properties.getProperty(key, defaultValue);
    }
	
	/**
	 * *********
	 * @return properties
	 */
	public static Properties getProperties(){
        return properties;
    }
	
	/**
	 * 
	 * @return Map<String,ArrayList<String>>
	 */
	public static Map<String, ArrayList<String>> getLocalDefineMap() {
		return localDefineMap;
	}
	
	/**
	 * 
	 * @param defineMap
	 */
	public static void setLocalDefineMap(Map<String, ArrayList<String>> defineMap) {
		localDefineMap = defineMap;
	}
	/**
	 * 替换字体类型中的空格
	 * @param str
	 * @return
	 */
	public static String replaceCharacterSpace(String contentHtml) {
		List<String[]> toReplaces=new ArrayList<String[]>();
    	toReplaces.add(new String[]{"Comic&nbsp;Sans&nbsp;MS","Comic Sans MS"});
    	toReplaces.add(new String[]{"Courier&nbsp;New","Courier New"});
    	toReplaces.add(new String[]{"Times&nbsp;New&nbsp;Roman","Times New Roman"});
    	toReplaces.add(new String[]{"Arial&nbsp;Black","Arial Black"});
    	toReplaces.add(new String[]{"Lucida&nbsp;Sans&nbsp;Typewriter", "Lucida Sans Typewriter"});
    	toReplaces.add(new String[]{"Microsoft&nbsp;Sans&nbsp;Serif", "Microsoft Sans Serif"});
    	toReplaces.add(new String[]{"MS&nbsp;UI&nbsp;Gothic", "MS UI Gothic"});
    	toReplaces.add(new String[]{"Arial&nbsp;Unicode&nbsp;MS", "Arial Unicode MS"});
    	for(String[] cons:toReplaces){
    		String src=cons[0];
    		String tgt=cons[1];
    		contentHtml = contentHtml.replaceAll(src, tgt);
    	}
		return contentHtml;
	}
	

	/**
	 * 判断Collection是否为空
	 * @param list
	 * @return boolean
	 */
	public static boolean isEmpty(Collection list){
		return !(list != null && list.size() > 0);
	}
    
     /**
      * 执行命令行参数
      * @param cmd 命令行参数
      * @return 成功返回true，失败返回false
      */
     public static boolean execCmd(String ip, String port) {
 		Runtime r = Runtime.getRuntime();
 		Process p = null;
 		String cmd = " cmd /c start telnet " + ip + " " + port + " ";
 		try {
 			p = r.exec(cmd);
 			Thread.sleep(10000);
			r.exec(" cmd /c start telnet " + ip + " ");
 			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));   
 	        String line = null;   
 	        while((line = br.readLine()) != null){  
 	           System.out.println(line);   
 	        }   
 	        br.close();
 			p.waitFor();
 			if (p.exitValue() != 0) {//非0为不成功
 				byte[] temp = new byte[1024];
 				InputStream in = p.getErrorStream();
 				in.read(temp);
 				System.out.println("EROOR CODE:"+p.exitValue());
 				return false;
 			} else {//0：成功
 				return true;
 			}
 		} catch (IOException e) {
 			e.printStackTrace();
 			return false;
 		} catch (InterruptedException e) {
 			e.printStackTrace();
 		}
 		return true;
 	}
     
   /**
    * 判断判断partNames是否包含dataType
    * @param partNames
    * @param dataType
    * @return boolean
    */
     public static boolean contain(Object[] partNames, Object dataType) {
 		if(partNames!=null){
 			for(Object ob:partNames){
 				if(ob.equals(dataType)){
 					return true;
 				}
 			}
 		}
 		return false;
 	}
     
     //********************************************************************************************************************
     //																				Ⅱ项目工具				
     //********************************************************************************************************************
     /**
      * 判断是否是手机号
      * @param mobile
      * @return boolean
      */
     public static boolean isMobilePhone(String mobile) {
    	if(mobile.startsWith("1000000")) return true;
 		Pattern p = Pattern.compile("^((13[0-9])|(15[0-9])|(14[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
 		Matcher m = p.matcher(mobile);
 		return m.matches();
 	}

     /**
      * 转码
      * @param s
      * @return string
      */
 	public static String encodeBASE64(String s) {
 		if (s == null)
 			return null;
 		return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
 	}

 	/**
 	 * 将 BASE64 编码的字符串 s 进行解码
 	 * @param s
 	 * @return string
 	 */
 	public static String decodeBASE64(String s) {
 		if (s == null)
 			return null;
 		BASE64Decoder decoder = new BASE64Decoder();
 		try {
 			byte[] b = decoder.decodeBuffer(s);
 			return new String(b);
 		} catch (Exception e) {
 			return null;
 		}
 	}
 	
 	/**
 	 * 
 	 * @param str
 	 * @return string
 	 */
 	public static String removeNonBmpUnicode(String str) {    
 	   if (Utils.isEmpty(str)) {    
 	       return "";    
 	   }    
 	   return str.replaceAll("[^\\u0000-\\uFFFF]", "");    
 	}

 	/**
 	 * 计算支付宝费用，0.5%手续费，最低1元；最高25元
 	 * @param money
 	 * @return
 	 */
 	public static double getCountFee(String money) {
 		if(Utils.isEmpty(money)) return 0;
 		Double mount = Double.valueOf(money);
 		if(mount <= 0) return 0;
 		Double countFee = mount * 0.005;
 		countFee = countFee < 1 ? 1 : countFee;
 		countFee = countFee > 25 ? 25 : countFee;
 		return countFee;
 	}
 	
 	/**
 	 * 测试
 	 * @param args
 	 */
// 	public static void main(String[] args){
// 		System.out.println("1=" + getCountFee("1"));
// 		System.out.println("10=" + getCountFee("10"));
// 		System.out.println("1000=" + getCountFee("1000"));
// 		System.out.println("10000=" + getCountFee("10000"));
// 	}

        public static String gainSuffix(String path) {
            int index=path.lastIndexOf(".");
            if(index>0){
                    String avatarSuffix=path.substring(index);
                    index = avatarSuffix.indexOf("?");
                    if(index > 0 ){
                            avatarSuffix = avatarSuffix.substring(0,index);
                    }
                    return avatarSuffix;
            }
            return null;
        } 
        public static String gainLastSuffix(String path, String lastSplitChar) {
            int index=path.lastIndexOf(lastSplitChar);
            if(index>0){
                    String avatarSuffix=path.substring(index);
                    index = avatarSuffix.indexOf("?");
                    if(index > 0 ){
                            avatarSuffix = avatarSuffix.substring(0,index);
                    }
                    return avatarSuffix;
            }
            return null;
        }

        public static String addZero2OrderTime(String orderTimeCode) {
            if(StringUtils.isEmpty(orderTimeCode)) return "";
            StringBuilder sb = new StringBuilder();
            if(orderTimeCode.length() < 17){
                sb.append(orderTimeCode);
                for(int i=0; i<17- orderTimeCode.length(); i++){
                    sb.append("0");
                }
            } else {
                return orderTimeCode; 
            }
            return sb.toString();
        }
        
   	 	/**
         * double类型数据加减
         * </p>
         * @param isSub 是否为减法
         * @param money
         * @param counterFee
         * @return
         */
    	public static Double doubleSubOrAdd(boolean isSub, String money, String counterFee) {
    		BigDecimal a1 = new BigDecimal(money);
    		BigDecimal b1 = new BigDecimal(counterFee);
    		if(isSub){
    			return a1.subtract(b1).doubleValue();
    		} else {
    			return a1.add(b1).doubleValue();
    		}
    	}

		public static void replaceTransType(String string) {
			StackTraceElement[] elements = Thread.currentThread().getStackTrace();
			System.out.println(elements[1]);
		}
}
